//
//  YKStatusTableViewCell.m
//  youkan
//
//  Created by 吴高烽 on 2018/10/17.
//  Copyright © 2018年 Honsintech. All rights reserved.
//

#import "YKStatusTableViewCell.h"
#import "YYLabel+WeiBo.h"
#import "WBStatusHelper.h"
#import "YYControl.h"
#import "YKUser.h"
@implementation YKStatusTitleView
- (instancetype)initWithFrame:(CGRect)frame{
    if (frame.size.width == 0 && frame.size.height == 0) {
        frame.size.width = kScreenWidth;
        frame.size.height = kWBCellTitleHeight;
    }
    self = [super initWithFrame:frame];
    
    _titleLabel = [YYLabel labelWB];
    _titleLabel.size = CGSizeMake(kScreenWidth-100, self.height);
    _titleLabel.left = kWBCellPadding;
    [self addSubview:_titleLabel];
    
    _closeButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [_closeButton setImage:[UIImage imageNamed:@"close_button"] forState:UIControlStateNormal];
    [_closeButton sizeToFit];
    _closeButton.right = kWBCellPadding;
    _closeButton.centerY = self.height/2;
    [self addSubview:_closeButton];
    
    CALayer *line = [CALayer layer];
    line.size = CGSizeMake(self.height, CGFloatFromPixel(1));
    line.bottom = self.height ;
    line.backgroundColor = kWBCellLineColor.CGColor;
    [self.layer addSublayer:line];
    self.exclusiveTouch = YES ;

    return self;
}

@end
@implementation WBStatusProfileView{
    BOOL _trackingTouch;
}
- (instancetype)initWithFrame:(CGRect)frame{
    if (frame.size.width == 0 && frame.size.height == 0) {
        frame.size.width = kScreenWidth;
        frame.size.height = kWBCellProfileHeight;
    }
    self = [super initWithFrame:frame];
    self.exclusiveTouch = YES;
    
    @weakify(self)
    _avatarView = [UIImageView new];
    _avatarView.size = CGSizeMake(40, 40);
    _avatarView.origin = CGPointMake(kWBCellPadding, kWBCellPadding+3);
    _avatarView.contentMode = UIViewContentModeScaleAspectFill;
    [self addSubview:_avatarView];
    
//    给头像添加灰色描边图层
    CALayer *avatarBorder = [CALayer layer];
    avatarBorder.frame = _avatarView.bounds;
    avatarBorder.borderWidth = CGFloatFromPixel(1);
    avatarBorder.borderColor = [UIColor colorWithWhite:0     alpha:0.090].CGColor;
    avatarBorder.cornerRadius = _avatarView.height/2;
    avatarBorder.shouldRasterize = YES;
    avatarBorder.rasterizationScale = kScreenScale;
    [_avatarView.layer addSublayer:avatarBorder];
    
    _avatarBadgeView = [UIImageView new];
    _avatarBadgeView.size = CGSizeMake(14, 14);
    _avatarBadgeView.center = CGPointMake(_avatarView.right-6, _avatarView.bottom-6);
    _avatarBadgeView.contentMode = UIViewContentModeScaleAspectFit;
    [self addSubview:_avatarBadgeView];
    
    _nameLabel = [YYLabel labelWB];
    _nameLabel.size = CGSizeMake(kWBCellNameWidth, 24);
    _nameLabel.left = _avatarView.right + kWBCellNamePaddingLeft;
    _nameLabel.centerY = 27;
    // 内容溢出部分剪除掉
    _nameLabel.lineBreakMode = NSLineBreakByClipping;
    _nameLabel.textVerticalAlignment = YYTextVerticalAlignmentCenter;
    [self addSubview:_nameLabel];
    
    _sourceLabel = [YYLabel labelWB];
    _sourceLabel.frame = _nameLabel.frame;
    _sourceLabel.centerY = 47 ;
    // 微博发布源的点击事件
    _sourceLabel.highlightTapAction = ^(UIView * _Nonnull containerView, NSAttributedString * _Nonnull text, NSRange range, CGRect rect) {
        YKLog(@"微博发布源的点击事件");
    };
    [self addSubview:_sourceLabel];
    
    return self;
}
- (void)setVerifyType:(WBUserVerifyType)verifyType{
    _verifyType = verifyType ;
    switch (verifyType) {
        case WBUserVerifyTypeStandard:{
            _avatarBadgeView.hidden = NO;
            _avatarBadgeView.image = [WBStatusHelper imageNamed:@"avatar_vip"];
        }break;
        case WBUserVerifyTypeClub:{
            _avatarBadgeView.hidden = NO;
            _avatarBadgeView.image = [WBStatusHelper imageNamed:@"avatar_grassroot"];
        }break;
        default:{
            _avatarBadgeView.hidden = YES ;
        }break;
    }
}
//GF 这里没有判断sourceLabel的响应，是怎么一回事
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    _trackingTouch = NO ;
//    获取点击后的任意一个点对象
    UITouch *t = touches.anyObject;
//    获取点击对象相对某个视图上点的位置
    CGPoint p = [t locationInView:_avatarView];
//    判断这个是否在这个视图上
    if (CGRectContainsPoint(_avatarView.bounds, p)) {
        _trackingTouch = YES ;
    }
    p = [t locationInView:_nameLabel];
    if (CGRectContainsPoint(_nameLabel.bounds, p) &&
        _nameLabel.textLayout.textBoundingRect.size.width > p.x) {
        _trackingTouch = YES;
    }
    if (!_trackingTouch) {
        [super touchesBegan:touches withEvent:event];
    }
}
- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    if(_trackingTouch){
//GF        实现代理的一些方法
//        if (<#condition#>) {
//            <#statements#>
//        }
    }else{
        [super touchesEnded:touches withEvent:event];
    }
}
- (void)touchesCancelled:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    if (!_trackingTouch) {// 没有跟踪的时候才取消
        [super touchesCancelled:touches withEvent:event];
    }
}
@end


@implementation WBStatusCardView{
    BOOL _isRetweet;
}
- (instancetype)initWithFrame:(CGRect)frame{
    if (frame.size.width == 0 && frame.size.height == 0) {
        frame.size.width = kScreenWidth;
        frame.origin.x = kWBCellPadding;
    }
    self = [super initWithFrame:frame];
    //    　　作用举例：UITableView的每个cell都需要使用exclusive，否则同时点击多个cell会触发每个视图的事件响应。手势识别会忽略此属性。
    self.exclusiveTouch = YES;
    
    _imageView = [UIImageView new];
    _imageView.clipsToBounds = YES;
    _imageView.contentMode = UIViewContentModeScaleAspectFill;
    _badgeImageView = [UIImageView new];
    _badgeImageView.clipsToBounds = YES;
    _badgeImageView.contentMode = UIViewContentModeScaleAspectFit;
    _label = [YYLabel new];
    _label.textVerticalAlignment = YYTextVerticalAlignmentCenter;
    _label.numberOfLines = 3;
    _label.ignoreCommonProperties = YES;
    _label.displaysAsynchronously = YES;
    _label.fadeOnAsynchronouslyDisplay = NO;
    _label.fadeOnHighlight = NO;
    _button = [UIButton buttonWithType:UIButtonTypeCustom];
    [self addSubview:_imageView];
    [self addSubview:_badgeImageView];
    [self addSubview:_label];
    [self addSubview:_button];
    self.backgroundColor = kWBCellInnerViewColor;
    self.layer.borderWidth = CGFloatFromPixel(1);
    self.layer.borderColor = [UIColor colorWithWhite:0.000 alpha:0.070].CGColor;
    return self;
}
//
//- (void)setWithLayout:(WBStatusLayout *)layout isRetweet:(BOOL)isRetweet {
//    WBPageInfo *pageInfo = isRetweet ? layout.status.retweetedStatus.pageInfo : layout.status.pageInfo;
//    if (!pageInfo) {
//        return;
//    }
//    self.height = isRetweet ? layout.retweetCardHeight : layout.cardHeight ;
//    _isRetweet = isRetweet;
//    switch (isRetweet ? layout.retweetCardType : layout.cardType) {
//        case WBStatusCardTypeNone:{
//
//        }break;
//        case WBStatusCardTypeNormal:{
//            self.width = kWBCellContentWidth;
//            if (pageInfo.typeIcon) {
//                _badgeImageView.hidden = NO ;
//                _badgeImageView.frame = CGRectMake(0, 0, 25, 25);
//                [_badgeImageView setImageWithURL:pageInfo.typeIcon placeholder:nil];
//            }else{
//                _badgeImageView.hidden = YES;
//            }
//            if (pageInfo.pagePic) {
//                _imageView.hidden = NO ;
//                if (pageInfo.typeIcon) {
//                    _imageView.frame = CGRectMake(0, 0, 100, 70);
//                } else {
//                    _imageView.frame = CGRectMake(0, 0, 70, 70);
//                }
//                [_imageView setImageWithURL:pageInfo.pagePic placeholder:nil];
//            } else {
//                _imageView.hidden = YES;
//            }
//            _label.hidden = NO;
//            _label.frame = isRetweet ? layout.retweetCardTextRect : layout.cardTextRect;
//            _label.textLayout = isRetweet?layout.retweetCardTextLayout : layout.cardTextLayout;
//            WBButtonLink *button = pageInfo.buttons.firstObject;
//            if (button.pic && button.name) {
//                _button.hidden = NO;
//                _button.size = CGSizeMake(60, 70);
//                _button.top = 0;
//                _button.right = self.width ;
//                [_button setTitle:button.name forState:UIControlStateNormal];
//                [_button setImageWithURL:button.pic forState:UIControlStateNormal placeholder:nil];
//            } else {
//                _button.hidden = YES;
//            }
//        }break;
//        case WBStatusCardTypeVideo:{
//            self.width = self.height;
//            _badgeImageView.hidden = YES;
//            _label.hidden = YES;
//            _imageView.frame = self.bounds;
//            [_imageView setImageWithURL:pageInfo.pagePic options:kNilOptions];
//            _button.hidden = NO;
//            _button.frame = self.bounds;
//            [_button setTitle:nil forState:UIControlStateNormal];
//            [_button cancelImageRequestForState:UIControlStateNormal];
//            [_button setImage:[WBStatusHelper imageNamed:@"multimedia_videocard_play"] forState:UIControlStateNormal];
//
//        }break;
//        default:
//            break;
//    }
//    self.backgroundColor = isRetweet ? [UIColor whiteColor] : kWBCellInnerViewColor;
//}
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    self.backgroundColor = kWBCellInnerViewHighlightColor;
}
- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    self.backgroundColor = _isRetweet ? [UIColor whiteColor]:kWBCellInnerViewColor;
//    if ([_cell.delegate respondsToSelector:@selector(cellDidClickCard:)]) {
//        [_cell.delegate cellDidClickCard:_cell];
//    }
}
- (void)touchesCancelled:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    self.backgroundColor = _isRetweet ? [UIColor whiteColor] : kWBCellInnerViewColor;
}
@end

@implementation WBStatusToolbarView
-(instancetype)initWithFrame:(CGRect)frame{
    if (frame.size.width == 0 && frame.size.height == 0) {
        frame.size.width = kScreenWidth ;
        frame.size.height = kWBCellToolbarHeight;
    }
    self = [super initWithFrame:frame];
    self.exclusiveTouch = YES ;
    _repostButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _repostButton.exclusiveTouch = YES ;
    _repostButton.size = CGSizeMake(CGFloatPixelRound(self.width/3.0), self.height);
    [_repostButton setBackgroundImage:[UIImage imageWithColor:kWBCellHighlightColor] forState:UIControlStateHighlighted];
    _commentButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _commentButton.exclusiveTouch = YES ;
    _commentButton.size = CGSizeMake(CGFloatPixelRound(self.width/3.0), self.height);
    _commentButton.left = CGFloatPixelRound(self.width / 3.0);
    [_commentButton setBackgroundImage:[UIImage imageWithColor:kWBCellHighlightColor] forState:UIControlStateHighlighted];
    
    _likeButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _likeButton.exclusiveTouch = YES ;
    _likeButton.size = CGSizeMake(CGFloatPixelRound(self.width/3.0), self.height);
    _likeButton.left = CGFloatPixelRound(self.width / 3.0 * 2.0);
    [_likeButton setBackgroundImage:[UIImage imageWithColor:kWBCellHighlightColor] forState:UIControlStateHighlighted];
    
    _repostImageView = [[UIImageView alloc] initWithImage:[WBStatusHelper imageNamed:@"timeline_icon_retweet"]];
    _repostImageView.centerY = self.height / 2;
    [_repostButton addSubview:_repostImageView];
    _commentImageView = [[UIImageView alloc] initWithImage:[WBStatusHelper imageNamed:@"timeline_icon_comment"]];
    _commentImageView.centerY = self.height / 2;
    [_commentButton addSubview:_commentImageView];
    _likeImageView = [[UIImageView alloc] initWithImage:[WBStatusHelper imageNamed:@"timeline_icon_unlike"]];
    _likeImageView.centerY = self.height / 2;
    [_likeButton addSubview:_likeImageView];
    
    
    _repostLabel = [YYLabel new];
    _repostLabel.userInteractionEnabled = NO;
    _repostLabel.height = self.height;
    _repostLabel.textVerticalAlignment = YYTextVerticalAlignmentCenter;
    _repostLabel.displaysAsynchronously = YES;
    _repostLabel.ignoreCommonProperties = YES;
    _repostLabel.fadeOnHighlight = NO;
    _repostLabel.fadeOnAsynchronouslyDisplay = NO;
    [_repostButton addSubview:_repostLabel];
    
    _commentLabel = [YYLabel new];
    _commentLabel.userInteractionEnabled = NO;
    _commentLabel.height = self.height;
    _commentLabel.textVerticalAlignment = YYTextVerticalAlignmentCenter;
    _commentLabel.displaysAsynchronously = YES;
    _commentLabel.ignoreCommonProperties = YES;
    _commentLabel.fadeOnHighlight = NO;
    _commentLabel.fadeOnAsynchronouslyDisplay = NO;
    [_commentButton addSubview:_commentLabel];
    
    _likeLabel = [YYLabel new];
    _likeLabel.userInteractionEnabled = NO;
    _likeLabel.height = self.height;
    _likeLabel.textVerticalAlignment = YYTextVerticalAlignmentCenter;
    _likeLabel.displaysAsynchronously = YES;
    _likeLabel.ignoreCommonProperties = YES;
    _likeLabel.fadeOnHighlight = NO;
    _likeLabel.fadeOnAsynchronouslyDisplay = NO;
    [_likeButton addSubview:_likeLabel];
    
    UIColor *dark = [UIColor colorWithWhite:0 alpha:0.2];
    UIColor *clear = [UIColor colorWithWhite:0 alpha:0];
    NSArray *colors = @[(id)clear.CGColor,(id)dark.CGColor, (id)clear.CGColor];
    NSArray *locations = @[@0.2, @0.5, @0.8];
    
    _line1 = [CAGradientLayer layer];
    _line1.colors = colors;
    _line1.locations = locations;
    _line1.startPoint = CGPointMake(0, 0);
    _line1.endPoint = CGPointMake(0, 1);
    _line1.size = CGSizeMake(CGFloatFromPixel(1), self.height);
    _line1.left = _repostButton.right;
    
    _line2 = [CAGradientLayer layer];
    _line2.colors = colors;
    _line2.locations = locations;
    _line2.startPoint = CGPointMake(0, 0);
    _line2.endPoint = CGPointMake(0, 1);
    _line2.size = CGSizeMake(CGFloatFromPixel(1), self.height);
    _line2.left = _commentButton.right;
    
    _topLine = [CALayer layer];
    _topLine.size = CGSizeMake(self.width, CGFloatFromPixel(1));
    _topLine.backgroundColor = kWBCellLineColor.CGColor;
    
    _bottomLine = [CALayer layer];
    _bottomLine.size = _topLine.size;
    _bottomLine.bottom = self.height;
    _bottomLine.backgroundColor = UIColorHex(e8e8e8).CGColor;
    
    [self addSubview:_repostButton];
    [self addSubview:_commentButton];
    [self addSubview:_likeButton];
    [self.layer addSublayer:_line1];
    [self.layer addSublayer:_line2];
    [self.layer addSublayer:_topLine];
    [self.layer addSublayer:_bottomLine];
    
//    @weakify(self);
//    [_repostButton addBlockForControlEvents:UIControlEventTouchUpInside block:^(id sender) {
//        WBStatusCell *cell = weak_self.cell;
//        if ([cell.delegate respondsToSelector:@selector(cellDidClickRepost:)]) {
//            [cell.delegate cellDidClickRepost:cell];
//        }
//    }];
//
//    [_commentButton addBlockForControlEvents:UIControlEventTouchUpInside block:^(id sender) {
//        WBStatusCell *cell = weak_self.cell;
//        if ([cell.delegate respondsToSelector:@selector(cellDidClickComment:)]) {
//            [cell.delegate cellDidClickComment:cell];
//        }
//    }];
//
//    [_likeButton addBlockForControlEvents:UIControlEventTouchUpInside block:^(id sender) {
//        WBStatusCell *cell = weak_self.cell;
//        if ([cell.delegate respondsToSelector:@selector(cellDidClickLike:)]) {
//            [cell.delegate cellDidClickLike:cell];
//        }
//    }];
    return self;
}
//- (void)setWithLayout:(WBStatusLayout *)layout{
//    _repostLabel.width = layout.toolbarRepostTextWidth;
//    _commentLabel.width = layout.toolbarCommentTextWidth;
//    _likeLabel.width = layout.toolbarLikeTextWidth;
//
//    _repostLabel.textLayout = layout.toolbarRepostTextLayout;
//    _commentLabel.textLayout = layout.toolbarCommentTextLayout;
//    _likeLabel.textLayout = layout.toolbarLikeTextLayout;
//    [self adjustImage:_repostImageView label:_repostLabel inButton:_repostButton];
//    [self adjustImage:_commentImageView label:_commentLabel inButton:_commentButton];
//    [self adjustImage:_likeImageView label:_likeLabel inButton:_likeButton];
//    _likeImageView.image = layout.status.attitudesStatus ? [self likeImage] : [self unlikeImage];
//}
//    这种方法用懒加载替换应该可以吧
- (UIImage *)likeImage {
    static UIImage *img;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        img = [WBStatusHelper imageNamed:@"timeline_icon_like"];
    });
    return img;
}

- (UIImage *)unlikeImage {
    static UIImage *img;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        img = [WBStatusHelper imageNamed:@"timeline_icon_unlike"];
    });
    return img;
}
- (void)adjustImage:(UIImageView *)image label:(YYLabel *)label inButton:(UIButton *)button{
    CGFloat imageWidth = image.bounds.size.width ;
    CGFloat labelWidth = label.width;
    CGFloat paddingMid = 5;
    CGFloat paddingSide = (button.width - imageWidth - labelWidth - paddingMid)/2.0;
    image.centerX = CGFloatPixelRound(paddingSide + imageWidth/2);
    label.right = CGFloatPixelRound(button.width - paddingSide);
}
//
//- (void)setLiked:(BOOL)liked withAnimation:(BOOL)animation{
//    WBStatusLayout *layout = _cell.statusView.layout;
//    if (layout.status.attitudesStatus == liked) {
//        return ;
//    }
//    UIImage *image = liked ? [self likeImage]:[self unlikeImage];
//    int newCount = layout.status.attitudesCount;
//    newCount = liked ? newCount + 1 : newCount - 1 ;
//    if (newCount < 0) {
//        newCount = 0;
//    }
//    if (liked && newCount < 1 ) {
//        newCount = 1;
//    }
//    NSString *newCountDesc = newCount > 0 ? [WBStatusHelper shortedNumberDesc:newCount]: @"赞" ;
//    UIFont *font = [UIFont systemFontOfSize:kWBCellToolbarFontSize];
//    YYTextContainer *container = [YYTextContainer containerWithSize:CGSizeMake(kScreenWidth, kWBCellToolbarHeight)];
//    container.maximumNumberOfRows = 1 ;
//    NSMutableAttributedString *likeText = [[NSMutableAttributedString alloc]initWithString:newCountDesc];
//    likeText.font = font;
//    likeText.color = liked ? kWBCellToolbarTitleHighlightColor : kWBCellToolbarTitleColor;
//    YYTextLayout *textLayout = [YYTextLayout layoutWithContainer:container text:likeText];
//    layout.status.attitudesStatus = liked;
//    layout.status.attitudesCount = newCount ;
//    layout.toolbarLikeTextLayout = textLayout;
//    
//    if (!animation) {
//        _likeImageView.image = image;
//        _likeLabel.width = CGFloatPixelRound(textLayout.textBoundingRect.size.width);
//        _likeLabel.textLayout = layout.toolbarLikeTextLayout;
//        [self adjustImage:_likeImageView label:_likeLabel inButton:_likeButton];
//        return;
//    }
//    [UIView animateWithDuration:0.2 delay:0 options:UIViewAnimationOptionBeginFromCurrentState | UIViewAnimationOptionCurveEaseInOut animations:^{
//        _likeImageView.layer.transformScale = 1.7;
//    } completion:^(BOOL finished) {
//        self.likeImageView.image = image;
//        _likeLabel.width = CGFloatPixelRound(textLayout.textBoundingRect.size.width);
//        _likeLabel.textLayout = layout.toolbarLikeTextLayout;
//        [self adjustImage:_likeImageView label:_likeLabel inButton:_likeButton];
//        [UIView animateWithDuration:0.2 delay:0 options:UIViewAnimationOptionBeginFromCurrentState| UIViewAnimationOptionCurveEaseInOut animations:^{
//            _likeImageView.layer.transformScale = 0.9 ;
//        } completion:^(BOOL finished) {
//            [UIView animateWithDuration:0.2 delay:0 options:UIViewAnimationOptionBeginFromCurrentState animations:^{
//                _likeImageView.layer.transformScale = 1;
//            } completion:^(BOOL finished) {
//                
//            }];
//        }];
//    }];
//}
@end


@implementation WBStatusTagView
- (instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    @weakify(self);
    _button = [UIButton buttonWithType:UIButtonTypeCustom];
    [_button setBackgroundImage:[UIImage imageWithColor:kWBCellToolbarTitleColor] forState:UIControlStateNormal];
    [_button setBackgroundImage:[UIImage imageWithColor:[UIColor colorWithWhite:0.00 alpha:0.200]] forState:UIControlStateHighlighted];
    [_button addBlockForControlEvents:UIControlEventTouchUpInside block:^(id  _Nonnull sender) {
        if ([weak_self.cell.delegate respondsToSelector:@selector(cellDidClickTag:)]) {
            [weak_self.cell.delegate cellDidClickTag:weak_self.cell];
        }
    }];
    _button.hidden = YES;
    [self addSubview:_button];
    _label = [YYLabel new];
    _label.textVerticalAlignment = YYTextVerticalAlignmentCenter;
    
    _label.highlightTapAction = ^(UIView * _Nonnull containerView, NSAttributedString * _Nonnull text, NSRange range, CGRect rect) {
        if ([weak_self.cell.delegate respondsToSelector:@selector(cell:didClickInLabel:textRange:)]) {
            [weak_self.cell.delegate cell:weak_self.cell didClickInLabel:(YYLabel *)containerView textRange:range];
        }
    };
    [self addSubview:_label];
    
    _imageView = [UIImageView new];
    _imageView.size = CGSizeMake(kWBCellTagPlaceHeight, kWBCellTagPlaceHeight);
    _imageView.image = [WBStatusHelper imageNamed:@"timeline_icon_locate"];
    _imageView.hidden = YES;
    [self addSubview:_imageView];
    _label.height = kWBCellTagPlaceHeight;
    _button.height = kWBCellTagPlaceHeight;
    self.height = kWBCellTagPlaceHeight;
    return self;
}
//
//- (void)setWithLayout:(WBStatusLayout *)layout {
//    if (layout.tagType == WBStatusTagTypePlace) {
//        _label.height = kWBCellTagPlaceHeight;
//        _imageView.hidden = NO;
//        _button.hidden = NO;
//        _label.left = _imageView.right + 6;
//        _label.width = layout.tagTextLayout.textBoundingRect.size.width + 6;
//        _label.textLayout = layout.tagTextLayout;
//        _label.userInteractionEnabled = NO;
//
//        self.width = _label.right;
//        _label.width = self.width;
//        _button.width = self.width;
//    } else if (layout.tagType == WBStatusTagTypeNormal) {
//        _imageView.hidden = YES;
//        _button.hidden = YES;
//
//        _label.left = 0;
//        _label.width = layout.tagTextLayout.textBoundingRect.size.width + 1;
//        _label.userInteractionEnabled = YES;
//        _label.textLayout = layout.tagTextLayout;
//    }
//
//}

@end

@implementation WBStatusView{
    BOOL _touchRetweetView;
}
// 初始化所有子控件
- (instancetype)initWithFrame:(CGRect)frame{
    if (frame.size.width == 0 && frame.size.height == 0) {
        frame.size.width = kScreenWidth;
        frame.size.height = 1;
    }
    self = [super initWithFrame:frame];
    self.backgroundColor = [UIColor clearColor];
    self.exclusiveTouch = YES ;
    @weakify(self);
    _contentView = [UIView new];
    _contentView.width = kScreenWidth;
    _contentView.height = 1;
    _contentView.backgroundColor = [UIColor whiteColor];
    
    static UIImage *topLineBG,*bottomLineBG;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        topLineBG = [UIImage imageWithSize:CGSizeMake(1, 3) drawBlock:^(CGContextRef  _Nonnull context) {
            CGContextSetFillColorWithColor(context, [UIColor blackColor].CGColor);
            CGContextSetShadowWithColor(context, CGSizeMake(0, 0), 0.8, [UIColor colorWithWhite:0 alpha:0.08].CGColor);
            CGContextAddRect(context, CGRectMake(-2, 3, 4, 4));
            CGContextFillPath(context);
        }];
        bottomLineBG = [UIImage imageWithSize:CGSizeMake(1, 3) drawBlock:^(CGContextRef  _Nonnull context) {
            CGContextSetFillColorWithColor(context, [UIColor blackColor].CGColor);
            CGContextSetShadowWithColor(context, CGSizeMake(0, 0.4), 2, [UIColor colorWithWhite:0 alpha:0.08].CGColor);
            CGContextAddRect(context, CGRectMake(-2, -2, 4, 2));
            CGContextFillPath(context);
        }];
        
    });
    [self addSubview:_contentView];
    UIImageView *topLine = [[UIImageView alloc] initWithImage:topLineBG];
    topLine.width = _contentView.width ;
    topLine.bottom = 0 ;
    topLine.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleBottomMargin ;
    [_contentView addSubview:topLine];
    
    UIImageView *bottomLine = [[UIImageView alloc]initWithImage:bottomLineBG];
    [_contentView addSubview:bottomLine];
    
    _titleView = [YKStatusTitleView new];
    _titleView.hidden = YES ;
    [_contentView addSubview:_titleView];
    _profileView = [WBStatusProfileView new];
    [_contentView addSubview:_profileView];
    _vipBackgroundView = [UIImageView new];
    _vipBackgroundView.size = CGSizeMake(kScreenWidth , 14.0);
    _vipBackgroundView.top = -2;
    _vipBackgroundView.contentMode = UIViewContentModeTopRight;
    //    _vipBackgroundView.hidden = YES ;
    [_contentView addSubview:_vipBackgroundView];
    
    _menuButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _menuButton.size = CGSizeMake(30, 30);
    [_menuButton setImage:[WBStatusHelper imageNamed:@"timeline_icon_more"] forState:UIControlStateNormal];
    [_menuButton setImage:[WBStatusHelper imageNamed:@"timeline_icon_more_highlighted"] forState:UIControlStateHighlighted];
    _menuButton.centerX = self.width - 20 ;
    _menuButton.centerY = 18 ;
    [_menuButton addBlockForControlEvents:UIControlEventTouchUpInside block:^(id  _Nonnull sender) {
        if ([weak_self.cell.delegate respondsToSelector:@selector(cellDidClickMenu:)]) {
            [weak_self.cell.delegate cellDidClickMenu:weak_self.cell];
        }
    }];
    [_contentView addSubview:_menuButton];
    
    _retweetBackgroundView = [UIView new];
    _retweetBackgroundView.backgroundColor = kWBCellInnerViewColor;
    _retweetBackgroundView.width = kScreenWidth;
    [_contentView addSubview:_retweetBackgroundView];
    
    _textLabel = [YYLabel new];
    _textLabel.left = kWBCellPadding;
    _textLabel.width = kWBCellContentWidth;
    _textLabel.textVerticalAlignment = YYTextVerticalAlignmentTop;
    _textLabel.displaysAsynchronously = YES;
    _textLabel.ignoreCommonProperties = YES;
    _textLabel.fadeOnAsynchronouslyDisplay = NO;
    _textLabel.fadeOnHighlight = NO;
    _textLabel.highlightTapAction = ^(UIView * _Nonnull containerView, NSAttributedString * _Nonnull text, NSRange range, CGRect rect) {
        if ([weak_self.cell.delegate respondsToSelector:@selector(cell:didClickInLabel:textRange:)]) {
            [weak_self.cell.delegate cell:weak_self.cell didClickInLabel:(YYLabel *)containerView textRange:range];
        }
    };
    [_contentView addSubview:_textLabel];
    
    _retweetTextLabel = [YYLabel new];
    _retweetTextLabel.left = kWBCellPadding;
    _retweetTextLabel.width = kWBCellContentWidth;
    _retweetTextLabel.textVerticalAlignment = YYTextVerticalAlignmentTop;
    _retweetTextLabel.displaysAsynchronously = YES;
    _retweetTextLabel.ignoreCommonProperties = YES;
    _retweetTextLabel.fadeOnAsynchronouslyDisplay = NO;
    _retweetTextLabel.fadeOnHighlight = NO;
    _retweetTextLabel.highlightTapAction = ^(UIView * _Nonnull containerView, NSAttributedString * _Nonnull text, NSRange range, CGRect rect) {
        if ([weak_self.cell.delegate respondsToSelector:@selector(cell:didClickInLabel:textRange:)]) {
            [weak_self.cell.delegate cell:weak_self.cell didClickInLabel:(YYLabel *)containerView textRange:range];
        }
    };
    [_contentView addSubview:_retweetTextLabel];
    
    NSMutableArray *picViews = [NSMutableArray new];
    for (int i = 0; i < 9; i++) {
        YYControl *imageView = [YYControl new];
        imageView.size = CGSizeMake(100, 100);
        imageView.hidden = YES;
        imageView.clipsToBounds = YES ;
        imageView.backgroundColor = kWBCellHighlightColor ;
        imageView.exclusiveTouch = YES ;
        imageView.touchBlock = ^(YYControl *view, YYGestureRecognizerState state, NSSet *touches, UIEvent *event) {
            //        }
            //        imageView.touchBlock = ^(YYControl *view, UIGestureRecognizerState state, NSSet *touches, UIEvent *event) {
            if (![weak_self.cell.delegate respondsToSelector:@selector(cell:didClickImageAtIndex:)]) {
                return ;
            }
            if (state == YYGestureRecognizerStateEnded) {
                UITouch *touch = touches.anyObject;
                CGPoint p = [touch locationInView:view];
                if (CGRectContainsPoint(view.bounds, p)) {
                    [weak_self.cell.delegate  cell:weak_self.cell didClickImageAtIndex:i];
                }
            }
        };
        
        UIView *badge = [UIImageView new];
        badge.userInteractionEnabled = NO;
        badge.contentMode = UIViewContentModeScaleAspectFit;
        badge.size = CGSizeMake(56/2, 36/2);
        badge.autoresizingMask = UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleLeftMargin;
        badge.right = imageView.width;
        badge.bottom = imageView.height;
        badge.hidden = YES;
        [imageView addSubview:badge];
        [picViews addObject:imageView];
        [_contentView addSubview:imageView];
    }
    _picViews = picViews;
    
    _cardView = [WBStatusCardView new];
    _cardView.hidden = YES ;
    [_contentView addSubview:_cardView];
    
    _tagView = [WBStatusTagView new];
    _tagView.left = kWBCellPadding;
    _tagView.hidden = YES;
    [_contentView addSubview:_tagView];
    
    _toolbarView = [WBStatusToolbarView new];
    [_contentView addSubview:_toolbarView];
    
    return self;
}
- (void)setLayout:(WBStatusLayout *)layout{
    _layout = layout ;
    self.height = layout.height;
    _contentView.top = layout.marginTop;
    _contentView.height = layout.height - layout.marginTop - layout.marginBottom;
    
    CGFloat top = 0 ;
    if (layout.titleHeight > 0) {
        _titleView.hidden = NO ;
        _titleView.height = layout.titleHeight;
        _titleView.titleLabel.textLayout = layout.titleTextLayout;
        top = layout.titleHeight;
    }else{
        _titleView.hidden = YES;
    }
    [_profileView.avatarView setImageWithURL:layout.status.user.avatarLarge placeholder:nil options:kNilOptions manager:[WBStatusHelper avatarImageManager] progress:nil transform:nil completion:nil];
    _profileView.nameLabel.textLayout = layout.nameTextLayout;
    _profileView.sourceLabel.textLayout = layout.sourceTextLayout;
    _profileView.verifyType = layout.status.user.userVerifyType;
    _profileView.height = layout.profileHeight;
    _profileView.top = top ;
    top += layout.profileHeight;
    
    NSURL *picBg = [WBStatusHelper defaultURLForImageURL:layout.status.picBg];
    __weak typeof(_vipBackgroundView) vipBackgroundView = _vipBackgroundView;
    [vipBackgroundView setImageWithURL:picBg placeholder:nil options:YYWebImageOptionAvoidSetImage completion:^(UIImage * _Nullable image, NSURL * _Nonnull url, YYWebImageFromType from, YYWebImageStage stage, NSError * _Nullable error) {
        if (image) {
            image = [UIImage imageWithCGImage:image.CGImage scale:2.0 orientation:image.imageOrientation];
            vipBackgroundView.image = image ;
        }
    }];
    
    _textLabel.top = top;
    _textLabel.height = layout.textHeight;
    _textLabel.textLayout = layout.textLayout;
    top += layout.textHeight;
    
    _retweetBackgroundView.hidden = YES;
    _retweetTextLabel.hidden = YES;
    _cardView.hidden = YES ;
    if (layout.picHeight ==0 && layout.retweetPicHeight == 0) {
        [self _hideImageViews];
    }
    //    优先级 转发 图片 卡片
    if (layout.retweetHeight > 0) {
        _retweetBackgroundView.top = top;
        _retweetBackgroundView.height = layout.retweetHeight;
        _retweetBackgroundView.hidden = NO;
        
        _retweetTextLabel.top = top;
        _retweetTextLabel.height = layout.retweetTextHeight;
        _retweetTextLabel.textLayout = layout.retweetTextLayout;
        _retweetTextLabel.hidden = NO;
        
        if (layout.retweetPicHeight > 0) {
            [self _setImageViewWithTop:_retweetTextLabel.bottom isRetweet:YES];
        }else{
            [self _hideImageViews];
            if (layout.retweetCardHeight > 0 ) {
                _cardView.top = _retweetTextLabel.bottom;
                _cardView.hidden = NO ;
//                [_cardView setWithLayout:layout isRetweet:YES];
            }
        }
    } else if (layout.picHeight > 0){
        [self _setImageViewWithTop:top isRetweet:NO];
    }else if (layout.cardHeight > 0 ){
        _cardView.top = top;
        _cardView.hidden = NO;
//        [_cardView setWithLayout:layout isRetweet:NO];
    }
    if (layout.tagHeight > 0){
        _tagView.hidden = NO;
//        [_tagView setWithLayout:layout];
        _tagView.centerY = _contentView.height - kWBCellToolbarHeight - layout.tagHeight/2;
    }else{
        _tagView.hidden = YES;
    }
    _toolbarView.bottom = _contentView.height;
//    [_toolbarView setWithLayout:layout];
}
- (void)_setImageViewWithTop:(CGFloat)imageTop isRetweet:(BOOL)isRetweet{
    CGSize picSize = isRetweet ? _layout.retweetPicSize : _layout.picSize ;
    NSArray *pics = isRetweet ? _layout.status.retweeted_status.pic_urls:_layout.status.pic_urls;
    int picsCount = (int)pics.count ;
    for (int i = 0 ; i< 9; i++) {
        UIView *imageView = _picViews[i];
        if (i >= picsCount) {
            [imageView.layer cancelCurrentImageRequest];
            imageView.hidden = YES;
        }else{
            CGPoint origin = {0};
            switch (picsCount) {
                case 1:{
                    origin.x = kWBCellPadding;
                    origin.y = imageTop;
                }break;
                case 4:{
                    origin.x = kWBCellPadding + (i%2)*(picSize.width + kWBCellPaddingPic);
                    origin.y = imageTop + (int)(i/2)*(picSize.height+kWBCellPaddingPic);
                }break;
                default:{
                    origin.x = kWBCellPadding + (i%3)*(picSize.width + kWBCellPaddingPic);
                    origin.y = imageTop + (int)(i/3)*(picSize.height+kWBCellPaddingPic);
                    
                }
                    break;
            }
            imageView.frame = (CGRect){.origin = origin, .size = picSize};
            imageView.hidden = NO;
            [imageView.layer removeAnimationForKey:@"contents"];
            WBPicture *pic = pics[i];
            UIView *badge = imageView.subviews.firstObject;
            switch (pic.largest.badgeType) {
                case WBPictureBadgeTypeNone:
                {
                    if (badge.layer.contents) {
                        badge.layer.contents = nil;
                        badge.hidden = YES;
                    }
                }break;
                case WBPictureBadgeTypeLong:{
                    badge.layer.contents = (__bridge id)([WBStatusHelper imageNamed:@"timeline_image_longimage"].CGImage);
                    badge.hidden = NO;
                }break;
                case WBPictureBadgeTypeGIF:{
                    badge.layer.contents = (__bridge id)([WBStatusHelper imageNamed:@"timeline_image_gif"].CGImage);
                    badge.hidden = NO;
                    
                }break;
                    //                default:
                    //                    break;
            }
            @weakify(imageView);
            [imageView.layer setImageWithURL:pic.bmiddle.url placeholder:nil options:YYWebImageOptionAvoidSetImage completion:^(UIImage * _Nullable image, NSURL * _Nonnull url, YYWebImageFromType from, YYWebImageStage stage, NSError * _Nullable error) {
                @strongify(imageView);
                if (!imageView) {
                    return ;
                }
                if (image && stage == YYWebImageStageFinished) {
                    int width = pic.bmiddle.width;
                    int height = pic.bmiddle.height;
                    //                    NSLog(@"$#%@",pic.bmiddle.url.absoluteString);
                    
                    CGFloat scale = (height/width)/(imageView.height/imageView.width);
                    if (scale<0.99 || isnan(scale)) {// 宽图则把左右两边裁减掉
                        imageView.contentMode = UIViewContentModeScaleAspectFill;
                        imageView.layer.contentsRect = CGRectMake(0, 0, 1, 1);
                    }else{ // 高图只保留顶部
                        imageView.contentMode = UIViewContentModeScaleToFill;
                        imageView.layer.contentsRect = CGRectMake(0, 0, 1, (float)width / height);
                    }
                    ((YYControl *)imageView).image = image;
                    if (from != YYWebImageFromMemoryCacheFast) {
                        CATransition *transition = [CATransition animation];
                        transition.duration = 0.15;
                        transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut];
                        transition.type = kCATransitionFade;
                        [imageView.layer addAnimation:transition forKey:@"contents"];
                    }
                }
            }];
        }
    }
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    UITouch *touch = touches.anyObject;
    CGPoint p = [touch locationInView:_retweetBackgroundView];
    BOOL insideRetweet = CGRectContainsPoint(_retweetBackgroundView.bounds, p);
    if (!_retweetBackgroundView.hidden && insideRetweet) {
        [_retweetBackgroundView performSelector:@selector(setBackgroundColor:) withObject:kWBCellHighlightColor afterDelay:0.15];
        _touchRetweetView = YES;
    } else {
        [_contentView performSelector:@selector(setBackgroundColor:) withObject:kWBCellHighlightColor afterDelay:0.15];
        _touchRetweetView = NO ;
    }
}
- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self touchesRestoreBackgroundColor];
    if (_touchRetweetView) {
        if ([_cell.delegate respondsToSelector:@selector(cellDidClickRetweet:)]) {
            [_cell.delegate cellDidClickRetweet:_cell];
        }
    } else {
        if ([_cell.delegate respondsToSelector:@selector(cellDidClick:)]) {
            [_cell.delegate cellDidClick:_cell];
        }
    }
    
}
- (void)touchesCancelled:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self touchesRestoreBackgroundColor];
}
- (void)_hideImageViews{
    for (UIImageView *imageView in _picViews) {
        imageView.hidden = YES;
    }
}
- (void)touchesRestoreBackgroundColor {
    [NSObject cancelPreviousPerformRequestsWithTarget:_retweetBackgroundView selector:@selector(setBackgroundColor:) object:kWBCellHighlightColor];
    [NSObject cancelPreviousPerformRequestsWithTarget:_contentView selector:@selector(setBackgroundColor:) object:kWBCellHighlightColor];
    
    _contentView.backgroundColor = [UIColor whiteColor];
    _retweetBackgroundView.backgroundColor = kWBCellInnerViewColor;
}
@end


@implementation YKStatusTableViewCell
- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    _statusView = [WBStatusView new];
    _statusView.cell = self;
    _statusView.titleView.cell = self;
    _statusView.profileView.cell = self;
    _statusView.cardView.cell = self;
    _statusView.toolbarView.cell = self;
    _statusView.tagView.cell = self;
    [self.contentView addSubview:_statusView];
    return self;
}
- (void)prepareForReuse{
    // ignore;
}
- (void)setLAyout:(WBStatusLayout *)layout{
    self.height = layout.height;
    self.contentView.height = layout.height;
    _statusView.layout = layout;
}

@end
